<!DOCTYPE html>
<html>

<head>
  <style>
    .search-container {
      position: relative;
      width: 400px;
      /* 控制搜索框和下拉框的整体宽度 */
      margin: 50px auto;
    }


    .search-input {
      width: 100%;
      padding: 12px 20px;
      border: 2px solid #9b59b6;
      border-radius: 25px;
      font-size: 16px;
      outline: none;
      transition: all 0.3s ease;
      background-color: #f8f6ff;
    }

    .search-input:focus {
      box-shadow: 0 0 8px rgba(155, 89, 182, 0.5);
    }

    .search-results {
      /* display: none; */
      position: absolute;
      width: 100%;
      /* 保持与搜索框同宽 */
      background: white;
      border: 1px solid #e0e0e0;
      border-radius: 8px;
      box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
      margin-top: 8px;
      z-index: 1000;
      /* 移除固定高度，改为自动高度 */
      max-height: 80vh;
      /* 防止过高超出视口 */
      overflow-y: auto;
      /* 内容过多时显示滚动条 */
    }

    .result-item {
      padding: 12px 20px;
      color: #2d3436;
      cursor: pointer;
      transition: background-color 0.2s;
      white-space: nowrap;
      /* 防止文字换行 */
      overflow: hidden;
      text-overflow: ellipsis;
      /* 文字过长显示省略号 */
    }


    .result-item:hover {
      background-color: #f5f3ff;
    }

    .search-icon {
      position: absolute;
      right: 20px;
      top: 50%;
      transform: translateY(-50%);
      color: #9b59b6;
    }

    .result-item.error {
      color: #e74c3c;
      background: #ffe6e6;
    }

    /* 加载状态样式 */
    .result-item:not(.error) {
      color: #666;
      font-style: italic;
    }
  </style>
</head>

<body>
  <div class="search-container">
    <input type="text" class="search-input" placeholder="搜索..." id="searchInput" autocomplete="new-password">
    <div class="search-results" id="searchResults"></div>
  </div>

  <script>

    // 初始化时强制清空
    const searchInput = document.getElementById('searchInput');
    searchInput.value = ''; // 确保初始值为空

    // 破解浏览器自动填充机制
    const randomId = 'input-' + Math.random().toString(36).substr(2, 5);
    searchInput.setAttribute('name', randomId);
    searchInput.setAttribute('id', randomId);
    const searchResults = document.getElementById('searchResults');
    let timeoutId;

    // 防抖函数（300ms）
    function debounce(func, delay) {
      return (...args) => {
        clearTimeout(timeoutId);
        timeoutId = setTimeout(() => func.apply(this, args), delay);
      };
    }

    // 获取搜索结果
    async function fetchResults(searchTerm) {
      try {
        // 添加加载状态
        searchResults.innerHTML = '<div class="result-item">搜索中...</div>';
        searchResults.style.display = 'block';

        const response = await fetch(
          `http://127.0.0.1:3000/api/getPoemsid?keyword=${encodeURIComponent(searchTerm)}`
        );

        if (!response.ok) throw new Error(`请求失败: ${response.status}`);

        const data = await response.json();

        searchResults.innerHTML = '';
        if (data.msg.length > 0) {
          data.msg.forEach(item => {
            const div = document.createElement('div');
            div.className = 'result-item';
            div.textContent = item.title || item; // 根据实际数据结构调整
            div.onclick = () => {
              searchInput.value = item.id || item; // 根据实际数据结构调整
              searchResults.style.display = 'none';
            };
            searchResults.appendChild(div);
          });
        } else {
          searchResults.innerHTML = '<div class="result-item">无结果</div>';
        }
      } catch (error) {
        console.error('搜索出错:', error);
        searchResults.innerHTML = `<div class="result-item error">${error.message}</div>`;
      }
    }

    // 添加事件监听（关键修复！）
    const debouncedSearch = debounce((term) => {
      if (term.length === 0) {
        searchResults.style.display = 'none';
        return;
      }
      fetchResults(term);
    }, 700);

    // 绑定输入事件
    searchInput.addEventListener('input', (e) => {
      debouncedSearch(e.target.value.trim());
    });

    // 点击外部关闭
    document.addEventListener('click', (e) => {
      if (!e.target.closest('.search-container')) {
        searchResults.style.display = 'none';
      }
    });

    // 初始隐藏结果框（关键修复！）
    searchResults.style.display = 'none';
  </script>
</body>

</html>